import React, { useContext, memo } from 'react';
import useRouter from '../../hooks/useRouter';
import { Form, Input, Checkbox, Button } from 'antd';
import useLocalStorage from '../../hooks/useLocalStorage';
import { ProviderContext } from '../../../store';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { login as loginReq } from 'api/Login'
import './index.less'

const LoginForm = () => {
    /** router 初始化 */
    const router = useRouter()

    /** reducer初始化 */
    const { state, asyncActions } = useContext(ProviderContext);
    console.log(state, asyncActions);

    /** 表单初始化 */
    const [form] = Form.useForm();
    const [storedName, setStoredName] = useLocalStorage('userName', '');
    const [remember, setRemember] = useLocalStorage('remember', false)
    form.setFieldsValue({ remember, userName: remember ? storedName : '' });

    /** 登录 */
    const login = () => {
        form.validateFields();
        const username = form.getFieldValue('userName');
        const password = form.getFieldValue('password')
        const remember = form.getFieldValue('remember');
        loginReq({ username, password }).then(() => {
            setStoredName(username);
            setRemember(remember)
            router.push('/');
        })
    };
    
    return (
        <Form form={form}>
            <Form.Item name="userName" rules={[{ required: true, message: '请输入用户名!' }]}>
                <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
            </Form.Item>
            <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
                <Input.Password placeholder="请输入密码" prefix={<LockOutlined />} onPressEnter={login} />
            </Form.Item>
            <Form.Item name="remember" valuePropName="checked">
                <Checkbox>记住用户名</Checkbox>
            </Form.Item>
            <Form.Item>
                <Button type="primary" danger className="login-btn" onClick={login}>
                    登陆
                </Button>
            </Form.Item>
        </Form>
    );
};
export default memo(LoginForm)